package com.shanghaionstar.home.life;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.more.response.PersonalInfoResponse;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.ImageCycleView;
import com.shanghaionstar.home.iview.IRenewalView;
import com.shanghaionstar.home.presenter.RenewalPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.shanghaionstar.home.life.AlarmManagerUtil.FIRST_SET_RENEWAL;

/**
 * Created by Rengui Lu on 2017/1/5.
 */
public class RenewalFragment extends BaseFragment implements IRenewalView{
    @FindViewById(R.id.title_tv)
    private TextView mTitleTv;
    @FindViewById(R.id.right_tv)
    private TextView mRightTv;
    @FindViewById(R.id.licence_date_rl)
    private RelativeLayout mLicenceDateRl;
    @FindViewById(R.id.progress_layout)
    private ProgressLayout mPl;
    @FindViewById(R.id.banner_icv)
    private ImageCycleView mBannerIcv;

    private RenewalPresenter mPresenter;
    private BaseActivity mActivity;

    private String mDateString = "";

    @Override
    public int getLayoutId() {
        return R.layout.owner_life_renewal;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (BaseActivity) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mTitleTv.setText(R.string.license_expiration);
        mDateString = PreferencesUtls.getInstance(mActivity).getString(Constants.LICENSE_EXPIRATION_DATE);
        mRightTv.setText(mDateString);
        initListener();
        mPresenter = new RenewalPresenter(mActivity.getScheduler());
        mPresenter.setView(this);
        mPresenter.start();

        mPresenter.commandData();
//        showAlarmManger(mActivity,System.currentTimeMillis()+5*1000,"5");
//        showAlarmManger(mActivity,System.currentTimeMillis()+10*1000,"10");
//        showAlarmManger(mActivity,System.currentTimeMillis()+15*1000,"15");
    }



    private void showDatePicker(final String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat(FinalConstants.DATE_FORMAT);
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        try {
            Date date = sdf.parse(dateString);
            calendar.setTime(date);
        } catch (Exception e) {
            e.printStackTrace();
            calendar.setTime(new Date(System.currentTimeMillis()));
        }
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int montyOfYear, int dayOfMonth) {
                StringBuilder sb = new StringBuilder();
                sb.append(year);
                sb.append("-");
                sb.append((montyOfYear + 1) < 10 ? "0" + (montyOfYear + 1) : (montyOfYear + 1));
                sb.append("-");
                sb.append(dayOfMonth<10?"0"+dayOfMonth:dayOfMonth);
                mDateString = sb.toString();
                mRightTv.setText(mDateString);
                mPresenter.updateUserInfo(mDateString);
                AlarmManagerUtil.notifyRenewal(getActivity(),mDateString);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }




    private void initListener() {
        mLicenceDateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.DriveLicense_expirydate.getStringValue());
                showDatePicker(mDateString);
            }
        });
    }

    @Override
    public void setLoading(boolean isLoading) {
        mPl.setVisibility(isLoading?View.VISIBLE:View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showAlertDialog(getActivity(),e.getMessage());
    }

    @Override
    public void onReponseSuccess(Object object) {
        if (object instanceof PersonalInfoResponse) {
            PersonalInfoResponse personalInfoResponse = (PersonalInfoResponse) object;
            String licenseExpireDate = TextUtils.isEmpty(personalInfoResponse.getLicenseExpireDate())?"":personalInfoResponse.getLicenseExpireDate();
            if(!TextUtils.isEmpty(licenseExpireDate)) {
                mRightTv.setText(licenseExpireDate);
                PreferencesUtls.getInstance(mActivity).putBoolean(FIRST_SET_RENEWAL,true);
            }else {
                PreferencesUtls.getInstance(mActivity).putBoolean(FIRST_SET_RENEWAL,false);
            }
        }
    }



    @Override
    public Activity onActivity() {
        return mActivity;
    }

    FunctionNameFindId[] functionNameFindIds = {FunctionNameFindId.DriveLicense_banner1,
            FunctionNameFindId.DriveLicense_banner2,
            FunctionNameFindId.DriveLicense_banner3,
            FunctionNameFindId.DriveLicense_banner4,
            FunctionNameFindId.DriveLicense_banner5};

    @Override
    public void onGetBanner(List<ResponBannerEntity> entities) {
        if (CommonUtil.isNull(entities)) {
//           discover_banner_iv.initBanner();
        } else {
            final DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.home_banner_failed)
                    .showImageForEmptyUri(R.drawable.home_banner_failed).showImageOnFail(R.drawable.home_banner_failed)
                    .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(false).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(100)).build();
            mBannerIcv.setVisibility(View.VISIBLE);
            mBannerIcv.setImageResources(entities, new ImageCycleView.ImageCycleViewListener() {
                @Override
                public void displayImage(Object o, ImageView imageView) {
                    if (o == null || imageView == null) {
                        mBannerIcv.setVisibility(View.GONE);
                        return;
                    }
                    ResponBannerEntity entity = (ResponBannerEntity) o;
                    ImageLoader.getInstance().displayImage(entity.getImgUrl(), imageView, options);
                }

                @Override
                public void onImageClick(Object o, int position, View imageView) {
                    if (o == null || imageView == null) {
                        mBannerIcv.setVisibility(View.GONE);
                        return;
                    }
                    if (position < functionNameFindIds.length)
                        BusinessUtil.sendReportByClickType(mActivity, functionNameFindIds[position].getStringValue());
                    if(o instanceof ResponBannerEntity)
                        mPresenter.onBannerClick((ResponBannerEntity) o);
                }
            });
        }
    }
}
